import BaseSprite from "../../../Script/Base/BaseSprite";
import { EResType } from "../../../Script/Common/Enum";
import EventID from "../../../Script/Common/EventID";
import { GlobalData } from "../../../Script/Common/GlobalData";
import { IMessage, IStoreItem } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import GameUtil from "../../../Script/Util/GameUtil";
import { LoadUtil } from "../../../Script/Util/LoadUtil";
import BaseConfig from "../../Base/BaseConfig";
import { AdManager } from "../../naodong/ads/AdManager";
import AudioManager, { ESoundType } from "../../Util/AudioManager";
import StoreItem from "./StoreItem";
import StoreUI from "./StoreUI";

const { ccclass, property } = cc._decorator;

// 小卖店玩法
@ccclass
export default class StockGame extends BaseSprite implements IMessage {

    @property({ type: cc.Node, tooltip: "进货小游戏开始页" })
    private startNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "进货小游戏页面" })
    private gameNode: cc.Node = null;

    @property({ type: cc.Label, tooltip: "倒计时文本" })
    private labTime: cc.Label = null;
    @property({ type: cc.Label, tooltip: "已获得n件货物" })
    private labStartRewardNum: cc.Label = null;

    @property({ type: cc.Node, tooltip: "货物父节点" })
    private stockItems: cc.Node = null;
    @property({ type: cc.Node, tooltip: "货物item" })
    private stockItem: cc.Node = null;
    @property({ type: cc.Node, tooltip: "奖励展示item" })
    private rewardItem: cc.Node = null;
    @property({ type: cc.Node, tooltip: "玩家" })
    private player: cc.Node = null;
    @property({ type: sp.Skeleton, tooltip: "玩家龙骨" })
    private ske: sp.Skeleton = null;

    @property({ type: [cc.Node], tooltip: "321倒计时" })
    private countTime: cc.Node[] = [];

    @property({ type: cc.Node, tooltip: "奖励弹窗" })
    private rewardsNode: cc.Node = null;
    @property({ type: cc.Node, tooltip: "继续进货按钮" })
    private btnStock: cc.Node = null;
    @property({ type: cc.Node, tooltip: "展示奖励页货物父节点" })
    private rewardsItems: cc.Node = null;
    @property({ type: cc.Label, tooltip: "展示奖励页的货物件数" })
    private labRewardNum1: cc.Label = null;

    @property({ type: cc.Node, tooltip: "rect" })
    private rect: cc.Node = null;

    private isGameStart: boolean = false;
    private isGameEnd: boolean = false;
    private remainTime: number = 30;
    private rewards: IStoreItem[] = [];

    recvMsg(cmd: number, data: any) {
        switch (cmd) {
            case EventID.TEST_CMD:
                {

                }
                break;
        }
    }

    protected onLoad() {
        super.onLoad();
        this.addMessage(EventID.TEST_CMD, this);

        this.restart();
    }

    protected onEnable() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchDown, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }
    protected onDisable() {
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchDown, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    public restart() {
        this.startNode.active = true;
        this.gameNode.active = false;
        this.rewardsNode.active = false;
        this.init();
    }

    private init() {
        this.rewards = [];
        this.remainTime = 30;
        this.isGameStart = false;
        this.isGameEnd = false;
        // 倒计时
        this.labTime.node.active = false;
        this.labTime.string = `${this.remainTime}`;
        // 获得货物数量
        this.labStartRewardNum.string = `${0}`;

        this.changeAnim('sanma_idle1');
    }

    private createStock() {
        const id = GameUtil.getRandomInteger(10101, 10110);
        const config = BaseConfig.instance.getItemInfoById(id);
        const temp = `${config.num}`.split("#");
        const num = GameUtil.getRandomInteger(temp[0], temp[1]);
        const x = Math.random() * 500 - 250;
        const item = cc.instantiate(this.stockItem);
        item.parent = this.stockItems;
        item.setPosition(cc.v2(x, 550));
        item.getComponent(StoreItem).setData('game', { id, num });
    }

    private updateStock(dt) {
        for (let i = this.stockItems.children.length - 1; i > -1; i--) {
            const item = this.stockItems.children[i];
            if (item) {
                item.y -= 300 * dt;
                if (item.y <= -GlobalData.design_height / 2) {
                    item.destroy();
                }

                // const items = BaseConfig.instance.getItemInfosByType(EDropType.Store, EBagType.Store);

                const intersect = GameUtil.intersect(this.player, item);
                if (intersect) {
                    item.destroy();
                    const data = item.getComponent(StoreItem).getRewardData();
                    this.rewards.push(data);

                    // 获得货物数量
                    const count = this.getTotalValue();
                    this.labStartRewardNum.string = `${count}`;
                }
            }
        }

        // 检测是否完成
        if (this.stockItems.children.length <= 0) {
            if (this.rewards.length > 0) {
                this.isGameEnd = true;
                this.showRewardNode(false);
                // 进货完成
                console.log("进货完成:", this.rewards);
            }
        }
    }

    private showRewardNode(isSpeed: boolean) {
        AudioManager.instance.playSound(ESoundType.RewardView, 2);
        this.rewardsNode.active = true;
        this.btnStock.active = !isSpeed;  // 快速进货隐藏'继续进货'按钮

        const datas: Map<number, number> = new Map();
        this.rewards.sort((o1, o2) => { return o1.id - o2.id });
        this.rewards.forEach((o) => {
            const num = datas.get(o.id);
            datas.set(o.id, !num ? o.num : num + o.num);
        });
        StoreUI.instance.setRewards(this.rewards);

        for (let i = this.rewardsItems.children.length - 1; i > -1; i--) {
            const item = this.rewardsItems.children[i];
            if (item) {
                item.destroy();
            }
        }

        for (let i = 10100; i < 10110; i++) {
            const id = i + 1;
            const num = datas.get(id);
            if (num && num > 0) {
                const item = cc.instantiate(this.rewardItem);
                item.parent = this.rewardsItems;
                item.active = true;
                // 名字
                const config = BaseConfig.instance.getItemInfoById(id);
                const name = cc.find("name", item).getComponent(cc.Label);
                name.string = `${config.name}`;
                // 数量
                const lab = cc.find("value", item).getComponent(cc.Label);
                lab.string = `${num}`;
                const icon = cc.find("icon", item).getComponent(cc.Sprite);
                LoadUtil.instance.setSpriteFrame(icon, EResType.Item, id, 82, 82);
            }
        }
        datas.clear();

        // 货物数量
        const count = this.getTotalValue();
        this.labRewardNum1.string = `${count}`;
    }

    private getTotalValue() {
        let count = 0;
        this.rewards.forEach((o) => {
            count += o.num;
        });
        return count;
    }

    private dt: number = 0;
    protected update(dt) {
        if (this.isGameEnd) return;
        this.updateStock(dt);

        if (!this.isGameStart) return;

        this.dt += dt;
        if (this.dt >= 0.5) {
            this.dt = 0;
            this.createStock();
            this.remainTime -= 0.5;
            if (this.remainTime <= 0) {
                this.isGameStart = false;
            }
            // 倒计时
            this.labTime.string = `${Math.ceil(this.remainTime)}`;
        }
    }

    private anim: string = '';
    private changeAnim(anim: 'sanma_idle1' | 'sanma_idle2' | 'sanma_run1' | 'sanma_run2') {
        if (this.anim === anim) {
            return;
        }
        this.anim = anim;

        // const isLoop = anim === 'sanma_idle1' || anim === 'sanma_idle2';
        this.ske.setAnimation(0, anim, true);
    }

    /**
     * 矩形相交
     * @param node1 
     * @param node2 
     * @returns 
     */
    public intersect(node1: cc.Node, node2: cc.Node) {
        if (!node1 || !node2) return false;
        const scale = SceneGame.instance.getRootScale();
        const pos1 = GameUtil.localConvertWorldPointAR(node1);
        const pos2 = GameUtil.localConvertWorldPointAR(node2);
        if (Math.abs((pos1.x - pos2.x) / scale) < (node1.width + node2.width) / 2 &&
            Math.abs((pos1.y - pos2.y) / scale) < (node1.height + node2.height) / 2) {
            return true;
        }
        return false;
    }

    private isClick: boolean = false;
    private onTouchDown(event: cc.Event.EventTouch, data: string) {
        const scale = SceneGame.instance.getRootScale();
        const pos = event.getLocation();
        this.rect.x = (pos.x - GlobalData.stage_width / 2) / scale;
        this.rect.y = (pos.y - GlobalData.stage_height / 2) / scale;
        const intersect = this.intersect(this.player, this.rect);
        if (intersect) {
            this.isClick = true;
        }
    }
    private onTouchMove(event: cc.Event.EventTouch, data: string) {
        if (!this.isClick) return;
        const scale = SceneGame.instance.getRootScale();
        const pos = event.getLocation();
        this.player.x = (pos.x - GlobalData.stage_width / 2) / scale;
        if (this.player.x < -220) {
            this.player.x = -220;
        }
        if (this.player.x > 220) {
            this.player.x = 220;
        }
        this.changeAnim('sanma_run1');
    }
    private onTouchEnd(event: cc.Event.EventTouch, data: string) {
        this.isClick = false;
        this.changeAnim('sanma_idle1');
    }
    private onTouchCancel(event: cc.Event.EventTouch, data: string) {
        this.isClick = false;
        this.changeAnim('sanma_idle1');
    }

    private async onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case 'btnStart':
            case 'btnStock':
                {
                    this.startNode.active = false;
                    this.gameNode.active = true;
                    this.rewardsNode.active = false;
                    this.init();
                    // 321开始
                    this.countTime.forEach((o) => { o.active = false; });
                    await GameUtil.sleep(500);
                    this.countTime[0].active = true;
                    await GameUtil.sleep(1000);
                    this.countTime[0].active = false;
                    this.countTime[1].active = true;
                    await GameUtil.sleep(1000);
                    this.countTime[1].active = false;
                    this.countTime[2].active = true;
                    await GameUtil.sleep(1000);
                    this.countTime[2].active = false;
                    this.isGameStart = true;
                    this.labTime.node.active = true;
                }
                break;
            case 'mask':
                {
                    this.restart();
                }
                break;
            case 'btnCounter':
                {
                    StoreUI.instance.openOtherNode(1);
                }
                break;
            case 'btnSpeed':    // 快速进货
                {
                    // 播放视频
                    AdManager.showVideoAd(() => {
                        // 随机奖励种类
                        const kinds = [2, 5];
                        const kind = kinds[Math.floor(Math.random() * kinds.length)];
                        // 随机奖励id
                        const ids = [];
                        for (let i = 10100; i < 10110; i++) {
                            ids.push(i + 1);
                        }
                        ids.sort(() => Math.random() - 0.5);
                        console.log("ids", ids);

                        this.rewards = [];
                        for (let i = 0; i < kind; i++) {
                            // 随机奖励数量
                            const num = GameUtil.getRandomInteger(10, 20);
                            this.rewards.push({ id: ids[i], num: num });
                        }

                        this.isGameEnd = true;
                        this.showRewardNode(true);
                    });
                }
                break;
        }
    }
}